import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class RotatePage extends StatefulWidget {
  const RotatePage({Key? key}) : super(key: key);

  @override
  _RotatePageState createState() => _RotatePageState();
}

class _RotatePageState extends State<RotatePage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _animationController;
  late final Animation _opacity;
  late final Animation _height;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 1))
          ..repeat(reverse: true);
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _opacity = Tween(begin: 0.5, end: 1).animate(_animationController);
    _height = Tween<double>(begin: 200, end: 300)
        .chain(CurveTween(curve: Curves.bounceInOut))
        .animate(_animationController);
    return Scaffold(
      appBar: AppBar(title: Text('Rotate')),
      body: Center(
          child: Column(children: [
        ...List.generate(
          5,
          (i) => SlideContainer(
            animationController: _animationController,
            color: Colors.teal,
            interval: Interval(i * 0.2, i * 0.2 + 0.2),
          ),
        ),
        AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return Opacity(
              opacity: _opacity.value,
              child: Container(
                alignment: Alignment.center,
                color: Colors.amber,
                width: 300,
                height: _height.value,
                child: child,
              ),
            );
          },
          child: const Text(
            'Rotate',
            style: TextStyle(fontSize: 70),
          ),
        )
      ])),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: () {
      //     _animationController.repeat(reverse: true);
      //   },
      //   child: Icon(Icons.refresh),
      // ),
    );
  }
}

class SlideContainer extends StatelessWidget {
  const SlideContainer(
      {super.key,
      required AnimationController animationController,
      required this.color,
      required this.interval})
      : _animationController = animationController;

  final AnimationController _animationController;
  final Interval interval;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: Tween(begin: Offset(-1, 0), end: Offset(1, 0))
          .chain(CurveTween(curve: Curves.elasticInOut))
          .chain(CurveTween(curve: interval))
          .animate(_animationController),
      // turns: _animationController.drive(Tween(begin: 0, end: 5)),
      child: Container(
        width: 100,
        height: 50,
        color: color,
      ),
    );
  }
}
